package com.ruoyi.system.service.impl;

import java.util.List;
import java.util.Collections;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.RoomMapper;
import com.ruoyi.system.domain.Room;
import com.ruoyi.system.service.IRoomService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import com.ruoyi.system.domain.RoomRecordmessage;
import com.ruoyi.system.mapper.RoomRecordmessageMapper;
import java.time.LocalDateTime;
import java.sql.Timestamp;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;

/**
 * 房间信息Service业务层处理
 * 
 * @author xyz
 * @date 2025-05-25
 */
@Service
public class RoomServiceImpl implements IRoomService 
{
    @Autowired
    private RoomMapper roomMapper;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private RoomRecordmessageMapper roomRecordmessageMapper;

    /**
     * 查询房间信息
     * 
     * @param id 房间信息主键
     * @return 房间信息
     */
    @Override
    public Room selectRoomById(String id)
    {
        Room room = roomMapper.selectRoomById(id);
        if (room != null) {
            processGroupUsers(Collections.singletonList(room));
        }
        return room;
    }

    /**
     * 查询房间信息列表
     * 
     * @param room 房间信息
     * @return 房间信息
     */
    @Override
    public List<Room> selectRoomList(Room room)
    {
        List<Room> rooms = roomMapper.selectRoomList(room);
        processGroupUsers(rooms);
        return rooms;
    }

    /**
     * 新增房间信息
     * 
     * @param room 房间信息
     * @return 结果
     */
    @Override
    public int insertRoom(Room room)
    {
        return roomMapper.insertRoom(room);
    }

    /**
     * 修改房间信息
     * 
     * @param room 房间信息
     * @return 结果
     */
    @Override
    public int updateRoom(Room room)
    {
        return roomMapper.updateRoom(room);
    }

    /**
     * 批量删除房间信息
     * 
     * @param ids 需要删除的房间信息主键
     * @return 结果
     */
    @Override
    public int deleteRoomByIds(String[] ids)
    {
        return roomMapper.deleteRoomByIds(ids);
    }

    /**
     * 删除房间信息信息
     * 
     * @param id 房间信息主键
     * @return 结果
     */
    @Override
    public int deleteRoomById(String id)
    {
        return roomMapper.deleteRoomById(id);
    }

    /**
     * 根据用户ID查询所在房间信息
     * 
     * @param userId 用户ID
     * @return 房间信息列表
     */
    @Override
    public List<Room> selectRoomsByUserId(String userId)
    {
        List<Room> rooms = roomMapper.selectRoomsByUserId(userId);
        processGroupUsers(rooms);
        return rooms;
    }

    /**
     * 处理组内用户信息
     */
    private void processGroupUsers(List<Room> rooms) {
        if (rooms == null || rooms.isEmpty()) {
            return;
        }

        for (Room room : rooms) {
            if (StringUtils.isNotBlank(room.getGroupName())) {
                String[] userIds = room.getGroupName().split(",");
                List<SysUser> groupUsers = new ArrayList<>();
                
                for (String userId : userIds) {
                    if (StringUtils.isNotBlank(userId)) {
                        SysUser user = userService.selectUserById(Long.parseLong(userId.trim()));
                        if (user != null) {
                            groupUsers.add(user);
                        }
                    }
                }
                
                room.setGroupNameList(groupUsers);
            }
        }
    }

    /**
     * 备份并清空房间信息
     */
    @Override
    @Transactional
    public void backupAndClearRoom() {
        List<Room> allRooms = roomMapper.selectRoomList(new Room());
        
        // 计算前一天的备份时间（当前时间减去24小时）
        long yesterdayMillis = System.currentTimeMillis() - (24 * 60 * 60 * 1000);
        Timestamp backupTime = new Timestamp(yesterdayMillis);
        
        for (Room room : allRooms) {
            RoomRecordmessage record = new RoomRecordmessage();
            // 字段拷贝
            record.setRoomId(room.getId() == null ? null : Long.valueOf(room.getId()));
            record.setArea(room.getArea());
            record.setPrice(room.getPrice());
            record.setStatus(room.getStatus());
            record.setGroupName(room.getGroupName());
            record.setPurpose(room.getPurpose());
            record.setBookerId(room.getBookerId());
            record.setServiceStaffId(room.getServiceStaffId());
            record.setDjId(room.getDjId());
            record.setStartTime(room.getStartTime());
            record.setEndTime(room.getEndTime());
            record.setBookerEntryCount(room.getBookerEntryCount());
            record.setServiceStaffEntryCount(room.getServiceStaffEntryCount());
            record.setDjEntryCount(room.getDjEntryCount());
            record.setTotalAmount(room.getTotalAmount());
            record.setDiscount(room.getDiscount());
            record.setServiceStaffPayment(room.getServiceStaffPayment());
            record.setDjPayment(room.getDjPayment());
            record.setSalespersonPayment(room.getSalespersonPayment());
            record.setAa(room.getAa());
            record.setBb(room.getBb());
            record.setCc(room.getCc());
            record.setRemark(room.getRemark());
            record.setFeedback(room.getRemark());
            record.setEe(room.getEe());
            record.setFf(room.getFf());
            record.setCreatedAt(room.getCreatedAt()); // 备份开始时间
            record.setRecordTime(backupTime);
            roomRecordmessageMapper.insertRoomRecordmessage(record);
        }
        // 清空除id、cc、area、price以外的字段
        roomMapper.clearRoomFieldsExceptCcAreaPrice();
    }

    /**
     * 翻台功能 - 备份指定房间信息到记录表并清空当前房间
     */
    @Override
    @Transactional
    public void flipTable(String roomId) {
        // 获取指定房间信息
        Room room = roomMapper.selectRoomById(roomId);
        if (room == null) {
            throw new RuntimeException("房间不存在");
        }
        
        // 创建房间记录
        RoomRecordmessage record = new RoomRecordmessage();
        // 字段拷贝
        record.setRoomId(room.getId() == null ? null : Long.valueOf(room.getId()));
        record.setArea(room.getArea());
        record.setPrice(room.getPrice());
        record.setStatus(room.getStatus());
        record.setGroupName(room.getGroupName());
        record.setPurpose(room.getPurpose());
        record.setBookerId(room.getBookerId());
        record.setServiceStaffId(room.getServiceStaffId());
        record.setDjId(room.getDjId());
        record.setBookerName(room.getBookerName());
        record.setServiceStaffName(room.getServiceStaffName());
        record.setDjName(room.getDjName());
        record.setStartTime(room.getStartTime());
        record.setEndTime(room.getEndTime());
        record.setBookerEntryCount(room.getBookerEntryCount());
        record.setServiceStaffEntryCount(room.getServiceStaffEntryCount());
        record.setDjEntryCount(room.getDjEntryCount());
        record.setTotalAmount(room.getTotalAmount());
        record.setDiscount(room.getDiscount());
        record.setServiceStaffPayment(room.getServiceStaffPayment());
        record.setDjPayment(room.getDjPayment());
        record.setSalespersonPayment(room.getSalespersonPayment());
        record.setAa(room.getAa());
        record.setBb(room.getBb());
        record.setCc(room.getCc());
        record.setRemark(room.getRemark());
        record.setFeedback(room.getRemark());
        record.setEe(room.getEe());
        record.setFf(room.getFf());
        record.setCreatedAt(room.getCreatedAt()); // 备份开始时间
        record.setRecordTime(new Date());
        
        // 插入房间记录
        roomRecordmessageMapper.insertRoomRecordmessage(record);
        
        // 清空当前房间信息（保留id、cc、area、price）
        roomMapper.clearRoomFieldsExceptCcAreaPriceById(roomId);
    }
}
